package com.atguigu.PracticalProject.app;
import com.atguigu.PracticalProject.common.Constant;
import com.atguigu.PracticalProject.util.FlinkSourceUtil;
import com.atguigu.PracticalProject.util.SQLUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public abstract class BaseSqlApp {
    public void init(int port, int p, String ckPathGroupIdJobName) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port); //设置端口号
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(p);  //设置并行度


//        env.enableCheckpointing(3000);
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/" + ckPathGroupIdJobName); //在hdfs存一个目录
//        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE); //设置严格一次模式
//        env.getCheckpointConfig().setCheckpointTimeout(20*1000); //设置超时时间
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1); //最大并发
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);  //最小间隔
//        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);//程序停止后设置Checkpoint保留

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //给sql job起名字
        tEnv.getConfig().getConfiguration().setString("pipeline.name",ckPathGroupIdJobName);

        handle(env,tEnv);

    }

    protected abstract void handle(StreamExecutionEnvironment env, StreamTableEnvironment tEnv);

    public void readOdsDb(StreamTableEnvironment tEnv, String groupId) {
        tEnv.executeSql("create table ods_db(" +
                "`database` string," +
                "`table` string," +
                "`type` string," +
                "`ts` bigint," +
                "`data` map<string,string>," +
                "`old` map<string,string>," +
                "`pt` as proctime() " + //lockup  join 用
                ")" + SQLUtil.getKafkaSource(Constant.TOPIC_ODS_DB,groupId));
    }
}
